<?php

namespace App\Http\Controllers\Laifei\Vip;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiVipStoreController extends Controller
{

    public function index()
    {
        $all = $this->all;
        $pageSize = $all['pageSize'] ?? 20;
        $pageNo = $all['pageNo'] ?? 1;


        try {

            $where = function ($query) use ($all) {
                $query->where('lv.is_delete','=',0);

                if(isset($all['openid'])){
                    $query->where('lu.openid','=',$all['openid']);
                }
                if(isset($all['nickname'])){
                    $query->where('lu.nickname','like','%'.$all['nickname'].'%');
                }
                if(isset($all['phone'])){
                    $query->where('lu.phone','=',$all['phone']);
                }
                if(isset($all['time']) && count($all['time']) === 2){
                    $query->whereBetween('lv.start_time',$all['time']);
                }
                if(isset($all['vip_id']) && count($all['vip_id'])){
                    $query->whereIn('lv.vip_id',$all['vip_id']);
                }
            };


            $total = DB::table('laifei_vip as lv')
                ->leftJoin('lottery_users as lu','lv.we_id','=','lu.we_id')
                ->where($where)
                ->count();


            $info = DB::table('laifei_vip as lv')
                ->leftJoin('lottery_users as lu','lv.we_id','=','lu.we_id')
                ->leftJoin('laifei_sys_vip as lsv','lv.vip_id','=','lsv.vip_id')
                ->leftJoin('laifei_adviser_user as lau',function($join){
                    $join->on('lv.we_id','=','lau.we_id')->where('lau.is_delete','=',0);
                })
                ->leftJoin('laifei_sys_adviser as lsa','lau.ad_id','=','lsa.ad_id')
                ->where($where)
                ->select('lv.v_id','lv.we_id','lv.vip_id','lv.total_month','lv.continue_times','lv.start_time','lv.end_time','lv.created_at as begin_time',
                    'lu.openid','lu.nickname','lu.phone',
                    'lsa.ad_id','lsv.subtitle','lsa.name as adviser')
                ->orderByDesc('lv.v_id')
                ->skip(($pageNo - 1) * $pageSize)
                ->take($pageSize)
                ->get()
                ->map(function($item){
                    $item->status = strtotime($item->end_time) > time();
                    $item->status_str = $item->status? '有效': '无效';
                    return $item;
                })
                ->toArray();

            return $this->setReturnJson(0,'success',['total'=>$total,'info'=>$info]);
        } catch (\Exception $e) {
            Log::error(LaifeiVipStoreController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'查询失败');
        }

    }

}
